package com.quanyue.haircut.user.service.impl;

import com.quanyue.auto.cache.core.CacheService;
import com.quanyue.auto.web.Principal;
import com.quanyue.haircut.domain.constant.CacheConstants;
import com.quanyue.haircut.domain.entity.User;
import com.quanyue.haircut.user.mapper.UserMapper;
import com.quanyue.haircut.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CacheService cacheService;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public User findByName(String name) {
        return userMapper.findByName(name);
    }

    @Override
    public User findByOpenId(String openId) {
        return userMapper.findByOpenId(openId);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findOne(id);
    }

    @Override
    @Transactional
    public User add(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setModifyTime(user.getCreateTime());
        userMapper.insert(user);
        return user;
    }

    @Override
    public void update(User user) {
        userMapper.updateSelective(user);
    }

    @Override
    public List <User> userList() {
        return userMapper.findAllValid();
    }


    @PostConstruct
    public void initSessionCache() {
        Map <String, Principal> map = new ConcurrentHashMap <>();
        cacheService.set(CacheConstants.SESSION_CACHE.name(), map);
    }
}
